#region Copyright

// // ======================================================
// //     Copyright (c) 2011 Toulr All rights reserved.
// //    
// //     The use and distribution terms for this software are contained in the file
// //     named license.txt, which can be found in the root of this distribution.
// //     By using this software in any fashion, you are agreeing to be bound by the
// //     terms of this license.
// //    
// //     You must not remove this notice, or any other, from this software.
// // ======================================================

#endregion

#region Using Namespaces

using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;

#endregion

namespace Toulr.Util.Configuration
{

    #region

    #endregion

    /// <summary>
    ///   the XML helper
    /// </summary>
    /// <Author> James Cheung</Author>
    /// <DateTime>2008/11/3 9:16</DateTime>
    public class XmlHelper
    {
        /// <summary>
        ///   Selects the element by X path string.
        /// </summary>
        /// <param name = "xmlDocument">The XML document.</param>
        /// <param name = "xPathString">The X path string.</param>
        /// <param name = "namespaceManager">The namespace manager.</param>
        /// <returns></returns>
        public static XPathNavigator SelectElementByXPathString(XmlDocument xmlDocument, string xPathString,
                                                                XmlNamespaceManager namespaceManager)
        {
            if (xmlDocument != null)
            {
                XPathNavigator xPathNavigator = xmlDocument.CreateNavigator();
                return xPathNavigator.SelectSingleNode(xPathString, namespaceManager);
            }

            return null;
        }

        /// <summary>
        ///   Selects the specified XML elements in document.
        /// </summary>
        /// <param name = "xmlDocument">The XML document.</param>
        /// <param name = "xpath">The xpath.</param>
        /// <param name = "namespaceManager">The namespace manager.</param>
        /// <returns></returns>
        /// <Author> James Cheung</Author>
        /// <DateTime>2008/11/3 9:15</DateTime>
        public static XPathNodeIterator Select(XmlDocument xmlDocument, string xpath,
                                               XmlNamespaceManager namespaceManager)
        {
            if (xmlDocument != null)
            {
                XPathNavigator xPathNavigator = xmlDocument.CreateNavigator();
                return xPathNavigator.Select(xpath, namespaceManager);
            }
            return null;
        }

        /// <summary>
        ///   Gets the XML elements by tag.
        /// </summary>
        /// <param name = "sourceElemenet">The source elemenet.</param>
        /// <param name = "targetName">Name of the target.</param>
        /// <returns></returns>
        public static XmlNodeList GetXmlElementsByTag(XmlElement sourceElemenet, string targetName)
        {
            return sourceElemenet.GetElementsByTagName(targetName);
        }

        /// <summary>
        ///   Gets the first child element with the specified tag name.
        /// </summary>
        /// <param name = "sourceElemenet">The source elemenet.</param>
        /// <param name = "targetName">Name of the target.</param>
        /// <returns></returns>
        public static XmlNode GetElementByTag(XmlElement sourceElemenet, string targetName)
        {
            try
            {
                return sourceElemenet.GetElementsByTagName(targetName)[0];
            }
            catch (XmlException ex)
            {
                throw new ToulrException(
                    "Can't found the tag named " + targetName, ex);
            }
        }

        /// <summary>
        ///   Saves the XML string as file.
        /// </summary>
        /// <param name = "xmlString">The XML string.</param>
        /// <param name = "fileName">Name of the file.</param>
        public static void SaveXmlStringAsFile(string xmlString, string fileName)
        {
            var xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xmlString);
            var fi = new FileInfo(fileName);
            {
                Directory.CreateDirectory(fi.DirectoryName);
                xmlDoc.Save(fileName);
            }
        }

        /// <summary>
        ///   Returns the node value.
        /// </summary>
        /// <param name = "filePath">The file path.</param>
        /// <param name = "nodeName">Name of the node.</param>
        /// <returns></returns>
        public static string ReturnNodeValue(string filePath, string nodeName)
        {
            string nodeValue = null;
            var fs = new FileStream(filePath, FileMode.Open);
            var xtr = new XmlTextReader(fs);
            try
            {
                while (!xtr.EOF)
                {
                    if (xtr.MoveToContent() == XmlNodeType.Element && xtr.Name == nodeName)
                    {
                        nodeValue = xtr.ReadElementString();
                    }
                    else
                    {
                        xtr.Read();
                    }
                }
            }
            catch (XmlException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                xtr.Close();
                fs.Close();
            }
            return nodeValue;
        }

        /// <summary>
        ///   Updates the node value.
        /// </summary>
        /// <param name = "filePath">The file path.</param>
        /// <param name = "nodeName">Name of the node.</param>
        /// <param name = "newValue">The new value.</param>
        /// <returns></returns>
        public static int UpdateNodeValue(string filePath, string nodeName, string newValue)
        {
            try
            {
                //Create the XmlDocument.
                var doc = new XmlDocument();
                var reader = new XmlTextReader(filePath) {WhitespaceHandling = WhitespaceHandling.All};
                reader.MoveToContent();
                doc.Load(reader);
                XmlNode root = doc.DocumentElement;
                if (root != null && nodeName != null)
                {
                    XmlNode node = root[nodeName];
                    if (node != null) node.InnerText = newValue;
                }
                doc.Save(filePath);
                reader.Close();
            }
            catch (XmlException ex)
            {
                Console.WriteLine(ex.Message);
                return 0;
            }
            return 1;
        }
    }
}